import   React, { useRef, useState ,useEffect} from 'react'
import { Button, Checkbox, Form, Input, Space , message } from 'antd';
import {  useNavigate } from 'react-router-dom'
import style from './style.module.scss'
import $api from '../../api';
import { sendCode, login } from '../../api/user';


const Login = ()=>{

    const navigate = useNavigate();
    const [formRef] = Form.useForm(); // 表单的ref对象
    

    const handleLogin =  async (res:any)=>{
        // console.log(res);
        const loginres = await login(res);
        console.log('loginres', loginres);
        const { data, success } = loginres.data;
        if(success){
            // 登录成功的话 保存token到本地
            window.localStorage.setItem('token', data.token)
            message.success('登录成功')
            navigate('/'); // 跳转到首页
        } else {
            message.warning('登录失败,你要找找自己的原因')
        }
    }

    const [ sendEnable,setSendEnable ] = useState(false);
    const [bttxt,setBttxt] = useState('发送验证码')
    const [counter,setCounter] = useState<any>();

    const getCode = async ()=>{
      // 主动的复制表单的校验
      try {
         await formRef.validateFields(['phone']); // 主动的去校验phone字段
         const phone = formRef.getFieldValue('phone');
         const res =  await  sendCode(phone);
         setSendEnable(true); // 不允许再发送短信了
         console.log('获取验证的结果', res)
         let timeCount = 10;
         const _ct =  setInterval(()=>{
           if(timeCount === 0){
               clearInterval(_ct);
               setCounter(null)
               setSendEnable(false);
               setBttxt('重新发送')
               return false;
           }
           setBttxt(`${timeCount}s后重新获取`)
           timeCount--;
         },1000)
         setCounter(_ct);

      } catch(e) {

      }
   

   
    }
    useEffect(()=>{
        // 在组件销毁的时候也去尝试主动的清楚定时器
        return function(){
            if(counter) clearInterval(counter);
        }
    },[])


    return (
        <div className='loginbg'>
            <div className={style.loginForm}>
                <Form form={formRef} labelCol={{ span: 4 }} onFinish={ handleLogin }>
                    <Form.Item 
                        label="手机号码" 
                        name="phone"
                        rules={[
                            // { required: true, message: '请输入手机号码' },
                            { validator(rule,value ){
                                if(/^1[3456789]\d{9}$/.test(value)){
                                      return   Promise.resolve()
                                }
                                return Promise.reject(new Error('请输入一个正确的手机号码'))
                             },  message:'请输入一个正确的手机号码', }
                        ]}
                    >
                        <Input  placeholder='填写手机号码'/>
                    </Form.Item>
                    <Form.Item 
                        label="验证码" 
                        name="code" 
                        rules={[
                            { validator(rule,value ){
                                if(value.length === 4){
                                      return   Promise.resolve()
                                }
                                return Promise.reject()
                             },  message:'填写正确的验证码', }
                        ]}
                    >
                        <Space.Compact style={{ width: '100%' }}>
                            <Input placeholder="输入收到的验证码" max={4} />
                            <Button disabled={sendEnable} type="primary" onClick={getCode}>{bttxt}</Button>
                        </Space.Compact>
                    </Form.Item>
                    <Form.Item>
                        <Button htmlType="submit">立即登录</Button>
                    </Form.Item>
                </Form>
                
            </div>
        </div>
    )
}

export default Login;